/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.bayu.graph;

import com.bayu.common.lib.CommonUtil;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import com.bayu.controller.MainController;
import com.bayu.services.dao.AvgStopTimeDao;
import com.bayu.services.dao.GraphPmsDao;
import com.bayu.services.entity.AvgStopTime;
import com.bayu.services.entity.GraphPms;
import java.awt.Color;
import java.io.OutputStream;
import java.util.List;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DatasetRenderingOrder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.CategoryItemRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.ui.TextAnchor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 *
 * @author joep
 */

@Controller
public class GraphPmsGraph {

    //private String query;
    GraphPmsDao graphPmsDao;
    AvgStopTimeDao avgStopTimeDao;

    @Autowired
    private void setGraphPmsDao(GraphPmsDao graphPmsDao){
      this.graphPmsDao = graphPmsDao;
    }

    @Autowired
    private void setavgStopTimeDao(AvgStopTimeDao avgStopTimeDao) {
        this.avgStopTimeDao = avgStopTimeDao;
    }

    @RequestMapping("/graph-pms-graph.png")
    private void graphPmsGraph (OutputStream stream) throws Exception{

        List maxValue= graphPmsDao.custom("select max(actualmould)+max(actualsand) from GraphPms where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
        List maxValue2 = graphPmsDao.custom("select max(frekwensi) from GraphPms where date between '"+MainController.startDate+"' and '"+MainController.endDate+"'");
        String strMax2 = maxValue2.get(0).toString();
        String strMax = maxValue.get(0).toString();
        System.out.println(strMax2+"-"+strMax);

        double max1 = Double.valueOf(strMax).doubleValue()+10;
        double max2 = Double.valueOf(strMax2).doubleValue()+1;



        double min = 0.0;
        //double max = maxtemp+2;
        JFreeChart chart = getPmsGraph(min, max1, max2);
        ChartUtilities.writeChartAsPNG(stream, chart, 1480,800);
    }


    private JFreeChart getPmsGraph(Double min,double max1,double max2){
       DefaultCategoryDataset dataset3 = graphPmsDataset3();

       String tgl1="";
       String tgl2="";
       String title = "STOP TIME MOULDING PMS";

      if(!MainController.startDate.equals("")){
          tgl1 = CommonUtil.formatStringDate(MainController.startDate);
          tgl2 = CommonUtil.formatStringDate(MainController.endDate);
          title = title+"\r\n"+ tgl1+"-"+tgl2;
      }
      final JFreeChart chart = ChartFactory.createBarChart(
            title,        // chart title
           "MONTH",               // domain axis label
           "Stop Time(menit)",                  // range axis label
            dataset3,                 // data
            PlotOrientation.VERTICAL,
            true,                     // include legend
            true,                     // tooltips?
            false                     // URL generator?  Not required...
        );
        chart.setBackgroundPaint(new Color(204, 255, 204));
        CategoryPlot plot = chart.getCategoryPlot();

        plot.setDomainAxisLocation(AxisLocation.BOTTOM_OR_LEFT);
        plot.setRangeAxisLocation(AxisLocation.TOP_OR_LEFT);

        CategoryItemRenderer renderer1 = plot.getRenderer();
        renderer1.setSeriesPaint(0, new Color(153,51,102));
        renderer1.setBaseNegativeItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE12, TextAnchor.TOP_CENTER));
        renderer1.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer1.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_CENTER));
        renderer1.setBaseItemLabelsVisible(true);

        DefaultCategoryDataset dataset1 = graphPmsDataset1();
        plot.setDataset(2, dataset1);
        CategoryItemRenderer renderer3 = new LineAndShapeRenderer();
        renderer3.setSeriesPaint(0, Color.RED);
        renderer3.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer3.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE8, TextAnchor.TOP_CENTER));
        renderer3.setBaseItemLabelsVisible(true);
        plot.setRenderer(2, renderer3);

        /*
         * Buat Axis 2
         */
        DefaultCategoryDataset dataset2 = graphPmsDataset2();
        ValueAxis axis2 = new NumberAxis("Frekwensi(kali)");
        axis2.setAutoRange(false);
        axis2.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        axis2.setRange(min,max2);

       plot.setRangeAxis(1, axis2);

    plot.setDataset(1, dataset2);
    plot.mapDatasetToRangeAxis(1, 1);
    CategoryItemRenderer renderer2 = new LineAndShapeRenderer();
    renderer2.setSeriesPaint(0, Color.BLUE);
    renderer2.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
    renderer2.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.INSIDE8, TextAnchor.TOP_CENTER));
    renderer2.setBaseItemLabelsVisible(true);
    plot.setRenderer(1, renderer2);

    plot.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD);

    NumberAxis rangeAxis = (NumberAxis)plot.getRangeAxis();
    rangeAxis.setAutoRange(false);
    rangeAxis.setRange(min,max1);
    rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

    return chart;
    }

    public DefaultCategoryDataset graphPmsDataset1(){
        String rowValue="BatasMax";
        DefaultCategoryDataset data1 = new DefaultCategoryDataset();
        String[] temp;
        String cat;
        List data = this.graphPmsDao.getAllByDate(MainController.startDate, MainController.endDate);
        List rata = this.avgStopTimeDao.custom("from AvgStopTime where jenis = 'batas max PMS'");

        /*
         * Ambil data tahun 2008,2009,2010
         */
        for (int j=0;j<rata.size();j++) {
            AvgStopTime st = (AvgStopTime)rata.get(j);
            data1.addValue(st.getAverage(), rowValue, "AVG" + Integer.toString(st.getTahun()));
            System.out.println("BatasMaxAvg "+Integer.toString(st.getTahun())+st.getAverage());
        }
        
        
        /*
         * Data bulanan
         */
        for(int i=0;i<data.size();i++){
          GraphPms dt = (GraphPms)data.get(i);
          temp = dt.getDate().toString().split("-");
          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));

          data1.addValue(dt.getBatasmax(), rowValue, cat);

          System.out.println("BatasMax "+dt.getBatasmax()+"-"+cat);
        }

        return data1;
    }

    public DefaultCategoryDataset graphPmsDataset2(){
        String rowValue="Frekwensi";
        DefaultCategoryDataset data2 = new DefaultCategoryDataset();
        String[] temp;
        String cat;
        List data = this.graphPmsDao.getAllByDate(MainController.startDate, MainController.endDate);
        List rata = this.avgStopTimeDao.custom("from AvgStopTime where jenis = 'frekwensi PMS'");

        for (int j=0;j<rata.size();j++) {
            AvgStopTime st = (AvgStopTime)rata.get(j);
            data2.addValue(st.getAverage(), rowValue, "AVG" + Integer.toString(st.getTahun()));
            System.out.println("FrekwensiAvg "+st.getAverage()+" Tahun "+ Integer.toString(st.getTahun()));
        }

        

        for(int i=0;i<data.size();i++){
          GraphPms dt = (GraphPms)data.get(i);
          temp = dt.getDate().toString().split("-");
          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));
          data2.addValue(dt.getFrekwensi(), rowValue, cat);
          System.out.println("Frekwensi "+dt.getFrekwensi()+"-"+cat);
        }

        return data2;
    }

    public DefaultCategoryDataset graphPmsDataset3() {
        String rowValue="Actual PMS";
        DefaultCategoryDataset data3 = new DefaultCategoryDataset();
        String[] temp;
        String cat;
        double value;
        List data = this.graphPmsDao.getAllByDate(MainController.startDate, MainController.endDate);
        List rata = this.avgStopTimeDao.custom("from AvgStopTime where jenis = 'actual PMS'");

        
        for (int j=0;j<rata.size();j++) {
            AvgStopTime st = (AvgStopTime)rata.get(j);
            data3.addValue(st.getAverage(), rowValue,"AVG" + Integer.toString(st.getTahun()));
            System.out.println("ActualPMSAvg "+Integer.toString(st.getTahun())+st.getAverage());
        }

        

        for(int i=0;i<data.size();i++){
          GraphPms dt = (GraphPms)data.get(i);
          temp = dt.getDate().toString().split("-");
          cat = CommonUtil.getMonthName((Integer.parseInt(temp[1])-1));
          value = (dt.getActualmould()+dt.getActualsand());
          data3.addValue(value, rowValue, cat);
          System.out.println("Actual PMS "+value+"-"+cat);
        }

        return data3;
    }

    


}
